<template>
  <a-card :bordered="false">
    <a-row :gutter="8">
      <a-col :span="5" style="overflow: scroll;max-height: 700px;"><search-tree :treeData="treeData" :dataList="dataList" :expandedKeys="expandedKeys" @select="handleSelect"></search-tree></a-col>
      <a-col :span="19">
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @submit="$refs.table.refresh(true)">
            <a-row :gutter="8">
              <a-col :md="5" :sm="15">
                <a-form-item><a-input type="number" placeholder="请输入年级" v-model="queryParam.grade" /></a-form-item>
              </a-col>
              <a-col :md="5" :sm="15">
                <a-form-item><a-input placeholder="请输入班级名称" v-model="queryParam.classesName" /></a-form-item>
              </a-col>
              <a-col :md="5" :sm="15">
                <a-form-item><a-input placeholder="请输入班主任姓名" v-model="queryParam.directorName" /></a-form-item>
              </a-col>
              <a-col :md="5" :sm="15">
                <a-form-item>
                  <a-select placeholder="请选择教育层次" v-model="queryParam.educationalLevel" allowClear>
                    <a-select-option v-for="(b, index) in educationalLevelList" :key="index" :value="b.dictValue">{{ b.dictLabel }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <span class="table-page-search-submitButtons">
                  <a-button type="primary" html-type="submit">查询</a-button>
                  <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div class="table-operator">
          <a-button v-if="addEnable" type="primary" icon="plus" @click="$refs.modal.add()">新建</a-button>
          <a-dropdown v-if="removeEnable && selectedRowKeys.length > 0">
            <a-popconfirm
              title="确定删除吗?"
              ok-text="是"
              cancel-text="否"
              @confirm="delByIds(selectedRowKeys)"
            >
              <a-button type="danger" icon="delete" >删除</a-button>
            </a-popconfirm>

          </a-dropdown>
        </div>
        <s-table
          size="default"
          ref="table"
          rowKey="classesId"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :columns="columns"
          :data="loadData">
          <span slot="classesStatus" slot-scope="text">{{ text | classesStatusFilter }}</span>
          <span slot="action" slot-scope="text, record">
            <a v-if="editEnabel" @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
              <a-popconfirm
                title="确定删除吗?"
                ok-text="是"
                cancel-text="否"
                @confirm="delByIds([record.classesId])"
              >
               <a v-if="removeEnable">删除</a>
            </a-popconfirm>
<!--            <a v-if="removeEnable" @click="delByIds([record.classesId])">删除</a>-->
          </span>
        </s-table>
      </a-col>
      <classes-modal ref="modal" @ok="handleOk" :deptTree="deptTree" :classesStatusList="classesStatusList" :educationalLevelList="educationalLevelList" />
    </a-row></a-card>
</template>

<script>
import { STable, SearchTree } from '@/components'
import { getSysClassesList, delSysClasses, getTreeForGreadDept } from '@/api/classes'
import { getDeptListEnable } from '@/api/system'
import ClassesModal from './modules/ClassesModal.vue'
import { checkPermission } from '@/utils/permissions'
import { getDictArray } from '@/utils/dict'

const classesStatusMap = {}
export default {
  name: 'TableList',
  components: {
    STable,
    ClassesModal,
    SearchTree
  },
  data () {
    return {
      deptTree: [],
      treeData: [],
      expandedKeys: [],
      dataList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      form: this.$form.createForm(this),
      mdl: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '年级',
          dataIndex: 'grade'
        },
        {
          title: '班级名称',
          dataIndex: 'classesName'
        },
        {
          title: '班主任',
          dataIndex: 'directorName'
        },
        {
          title: '系别名称',
          dataIndex: 'deptName'
        },
        {
          title: '专业名称',
          dataIndex: 'specialityName'
        },
        {
          title: '班级状态',
          dataIndex: 'classesStatus',
          scopedSlots: { customRender: 'classesStatus' }
        },
        {
          title: '操作',
          width: '200px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return getSysClassesList(Object.assign(parameter, this.queryParam))
      },
      selectedRowKeys: [],
      selectedRows: [],
      addEnable: checkPermission('system:classes:add'),
      editEnabel: checkPermission('system:classes:edit'),
      removeEnable: checkPermission('system:classes:remove'),
      classesStatusList: [],
      educationalLevelList: []
    }
  },
  filters: {
    classesStatusFilter (type) {
      return classesStatusMap[type]
    }
  },
  created () {
    getTreeForGreadDept().then(res => {
      console.log(res)
      if (res.code === 0) {
        this.buildtree1(res.data, this.treeData, '0')
        this.expandedKeys = res.data.map(m => m.parentId)
        this.dataList = res.data.map(m => {
          return { key: m.id, title: m.name }
        })
      }
    })
    getDictArray('st_educational_level').then(res => {
      this.educationalLevelList = res
    })
    getDeptListEnable().then(res => {
      const data = res.rows
      this.buildtree(data, this.deptTree, 0)
    })
    getDictArray('classes_status').then(res => {
      this.classesStatusList = res
      res.map(item => {
        classesStatusMap[item.dictValue] = item.dictLabel
      })
    })
  },
  methods: {
    handleSelect (selectedKeys, info) {
      var pa = selectedKeys[0]
      if (pa && pa.indexOf('d') !== -1) {
        if (pa.indexOf('g') !== -1) {
          pa = pa.substring(1).split('g')
          this.queryParam = {
            deptId: pa[0],
            grade: pa[1]
          }
        } else {
          this.queryParam = {
            deptId: pa.substring(1)
          }
        }
      } else {
        this.queryParam = {
          classesId: pa
        }
      }

      this.$refs.table.refresh(true)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleAdd () {
      this.$refs.modal.add()
    },
    handleEdit (record) {
      this.$refs.modal.edit(record)
    },
    handleOk () {
      this.$refs.table.refresh(true)
      console.log('handleSaveOk')
    },
    delByIds (ids) {
      delSysClasses({ ids: ids.join(',') }).then(res => {
        if (res.code === 0) {
          this.$message.success('删除成功')
          this.handleOk()
        } else {
          this.$message.error(res.msg)
        }
        this.selectedRowKeys = []
      })
    },
    buildtree1 (list, arr, parentId) {
      list.forEach(item => {
        if (item.parentId === parentId) {
          var child = {
            key: item.id,
            value: item.id, // value是给modal的select用的，2者属性不一样
            title: item.name,
            scopedSlots: { title: 'title' },
            children: []
          }
          this.buildtree1(list, child.children, item.id)
          if (child.children.length === 0) {
            delete child.children
          }
          arr.push(child)
        }
      })
    },
    buildtree (list, arr, parentId) {
      list.forEach(item => {
        if (item.parentId === parentId) {
          var child = {
            key: item.deptId,
            value: item.deptId, // value是给modal的select用的，2者属性不一样
            title: item.deptName,
            scopedSlots: { title: 'title' },
            children: []
          }
          this.buildtree(list, child.children, item.deptId)
          if (child.children.length === 0) {
            delete child.children
          }
          arr.push(child)
        }
      })
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
